#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

#include <stdio.h>
#include <string.h>

#define BSZ (32*1024)

char buf[BSZ];

//---------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
//---------------------------------------------------------------------------------
    if(argc<3) {
        printf("usage:\n");
        printf("\tsend file: %s <local file> <dest file> <ip>\n",argv[0]);
        printf("\tdelete remote file: %s <remote file> <ip>\n",argv[0]);
        return 0;
    }

    char *sfname=0, *dfname, *ip;

    if(argc>3) {
        sfname = argv[1];
        dfname = argv[2];
        ip = argv[3];
    } else {
        dfname = argv[1];
        ip = argv[2];
    }

    FILE *f;
    unsigned int fsz=0;

    if(sfname) {
        f = fopen(sfname, "rb");
        if(!f) {
            printf("Unable to open file %s\n",sfname);
            return 0;
        }
        fseek(f, 0, SEEK_END);
        fsz = ftell(f);
        fseek(f, 0, SEEK_SET);
    }

    int sock = socket( AF_INET, SOCK_STREAM, 0 );
    printf("Created Socket!\n");

    struct sockaddr_in sain;
    sain.sin_family = AF_INET;
    sain.sin_port = htons(80);
    sain.sin_addr.s_addr = inet_addr(ip);

    if(connect( sock,(struct sockaddr *)&sain, sizeof(sain) )==-1) {
        printf("connection error\n");
        return 0;
    }

    printf("Connected to server!\n");

    write(sock, dfname, strlen(dfname)+1);

    int i;
    for(i=0;i<4;i++) {
        unsigned char b = (fsz>>(8*i)) & 0xFF;
        write(sock,&b,1);
    }

    if(sfname) {
        unsigned long t0 = time(0);
        unsigned long t1 = t0;
        unsigned int total=0;
        while(!feof(f)) {
            unsigned long t2 = time(0);
            int rdlen = fread(buf,1,BSZ,f);
            total += rdlen;
            if(t1!=t2) {
                printf("enviando %d of %d (%d%%) %d kbps\n",total,fsz,(total*100)/fsz,total/((t2-t0)*1024) );
                t1=t2;
            }
            write(sock,buf,rdlen);
        }
        fclose(f);
    }

    printf("esperando confirmacao\n");
    read(sock, buf,4096);
    printf("done!\n");

    close(sock);

    return 0;
}


